package com.yry.security;

import java.security.Key;
import java.security.Security;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;

import org.apache.commons.codec.binary.Hex;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.junit.Test;
/**
 * 对称加密：3DES(Triple Des/DESede),应用广泛
 * 优点：
 * 密钥长度增长
 * 迭代次数提高
 * 
 * @author Administrator
 *
 */
public class Imooc3Des {
	
	private String srcStr = "imooc security 3des";
	public static void main(String[] args) {
		//1.密钥是什么？
		//2.加密；
		
		//3.解密；
	}
	
	/**
	 * JDK 3DES加密及解密；
	 */
	@Test
	public void jdk3Des(){
		try {
			//生成Key;
			KeyGenerator keyGenerator = KeyGenerator.getInstance("DESede");
			keyGenerator.init(168);//初始化KEY的长度112,168（默认）；
			//keyGenerator.init(new SecureRandom());//生成默认长度的KEY
			//产生密钥；
			SecretKey  secretKey = keyGenerator.generateKey();
			
			//获得密钥
			byte[] key = secretKey.getEncoded();
			
			//KEY转换
			DESedeKeySpec desKeySpec = new DESedeKeySpec(key);
			SecretKeyFactory factory=SecretKeyFactory.getInstance("DESede");
			Key convertSecretKey = factory.generateSecret(desKeySpec);
			
			
			//加密；
			Cipher cipher = Cipher.getInstance("DESede/ECB/PKCS5Padding");
			cipher.init(Cipher.ENCRYPT_MODE, convertSecretKey);
			byte[] result = cipher.doFinal(srcStr.getBytes());
			String resultStr = Hex.encodeHexString(result);
			System.out.println("JDK 3DES encrypt加密:"+resultStr);
			
			//解密
			cipher.init(Cipher.DECRYPT_MODE, convertSecretKey);
			result = cipher.doFinal(result);
			resultStr = new String(result);
			System.out.println("JDK 3DES DECRYPT解密: "+resultStr);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * BC,3DES
	 */
	@Test
	public void bc3Des(){
		try {
			Security.addProvider(new BouncyCastleProvider());
			//生成Key;
			KeyGenerator keyGenerator = KeyGenerator.getInstance("DESede","BC");
			keyGenerator.init(168);//初始化KEY的长度192/128/168(默认)；
			SecretKey  secretKey = keyGenerator.generateKey(); //产生密钥；
			byte[] key = secretKey.getEncoded(); //获得密钥
			
			//KEY转换
			DESedeKeySpec desKeySpec = new DESedeKeySpec(key);
			SecretKeyFactory factory=SecretKeyFactory.getInstance("DESede");
			Key convertSecretKey = factory.generateSecret(desKeySpec);
			
			//加密；
			Cipher cipher = Cipher.getInstance("DESede/ECB/PKCS7Padding");
			cipher.init(Cipher.ENCRYPT_MODE, convertSecretKey);
			byte[] result = cipher.doFinal(srcStr.getBytes());
			String resultStr = Hex.encodeHexString(result);
			System.out.println("BC 3DES encrypt加密:"+resultStr);
			
			//解密
			cipher.init(Cipher.DECRYPT_MODE, convertSecretKey);
			result = cipher.doFinal(result);
			resultStr = new String(result);
			System.out.println("BC 3DES DECRYPT解密: "+resultStr);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
